package com.yegs.quartz.service.impl;

import com.yegs.quartz.entity.StoreException;
import com.yegs.quartz.manager.QuartzManager;
import com.yegs.quartz.mysqlEntity.JobVo;
import com.yegs.quartz.mysqlRepository.JobRepository;
import com.yegs.quartz.service.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.util.List;

@Service
public class JobServiceImpl implements JobService {


    private static List<JobVo> list;

    @Autowired
    private JobRepository jobRepository;


    @Override
    public List<JobVo> findAll() {
        if(list==null){
            list = jobRepository.findAll();
        }
        return list;
    }

    @Override
    public void save(JobVo job) {
        if(job.getId()==null){
            job.setStates("false");
            jobRepository.save(job);
            list = jobRepository.findAll();
        }else if(job.getStates().equals("true")){
            throw new StoreException("请先暂停再修改");
        }else {
            jobRepository.save(job);
        }
    }

    @Override
    public void triggerStatus(Long id,String states) {
        JobVo job = jobRepository.getOne(id);
        job.setStates(states);
        QuartzManager.addJob(job);
        jobRepository.save(job);
        jobRepository.flush();
        list = jobRepository.findAll();
    }

    @Override
    public void del(Long id) {
        jobRepository.deleteById(id);
        list = jobRepository.findAll();
    }

    @Override
    public void trigger(Long id) {
        JobVo job = jobRepository.getOne(id);
        if(job==null){
            throw new StoreException("ID错误!");
        }
        if("true".equals(job.getStates())){
            job.setStates("false");
            QuartzManager.removeJob(job);
        }else{
            job.setStates("true");
            QuartzManager.addJob(job);
        }
        list = jobRepository.findAll();
    }
    @PreDestroy
    public void saveJobs(){
        for(JobVo jobVo:list){
            jobVo.setStates("false");
        }
        jobRepository.saveAll(list);
    }
    //TODO把所有数据存在系统，减少与服务器交互。

}
